package models

import (
	"errors"
	"fmt"
	"gitee.com/lzqysoft/ga_wz_backend/libs/seaweed"
	//	"os"
	"reflect"
	//	"strconv"
	"strings"
	"time"

	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
)

type Video struct {
	Id           string        `orm:"column(id);pk"`
	OrgName      string        `orm:"column(org_name);null"`
	Type         int           `orm:"column(type);null"`
	Scope        int           `orm:"column(scope);null"`
	Title        string        `orm:"column(title);null"`
	Url          string        `orm:"column(url);null"`
	Length       int           `orm:"column(length);null"`
	Longtime     string        `orm:"column(longtime);null"`
	Clicks       int           `orm:"column(clicks);null"`
	Lng          float64       `orm:"column(lng);null"`
	Lat          float64       `orm:"column(lat);null"`
	Address      string        `orm:"column(address);null"`
	Img          string        `orm:"column(img);null"`
	Status       int           `orm:"column(status)"`
	Remark       string        `orm:"column(remark);null"`
	Isdelete     int           `orm:"column(isdelete);default(0)"`
	Ctime        time.Time     `orm:"column(ctime);type(timestamp with time zone)"`
	Creater      string        `orm:"column(creater)"`
	Utime        time.Time     `orm:"column(utime);type(timestamp with time zone)"`
	Updater      string        `orm:"column(updater)"`
	Size         int           `orm:"column(size)"`
	User         []*User       `orm:"reverse(many)"`
	Organization *Organization `orm:"rel(fk)"`
	Dept         *Dept         `orm:"rel(fk)"`
}

func (t *Video) TableName() string {
	return "vid_video"
}

func init() {
	orm.RegisterModel(new(Video))
}

// AddVideo insert a new Video into database and returns
// last inserted Id on success.
func AddVideo(m *Video) (id int64, err error) {
	o := orm.NewOrm()
	id, err = o.Insert(m)
	return
}

// GetVideoById retrieves Video by Id. Returns error if
// Id doesn't exist
func GetVideoById(id string) (v *Video, err error) {
	o := orm.NewOrm()
	v = &Video{Id: id}
	if err = o.Read(v); err == nil {
		o.LoadRelated(v, "User")
		return v, nil
	}
	return nil, err
}

// GetAllVideo retrieves all Video matches certain condition. Returns empty list if
// no records exist
func GetAllVideo(query map[string]interface{}, fields []string, sortby []string, order []string,
	offset int64, limit int64) (ml []interface{}, count int64, err error) {
	o := orm.NewOrm()
	qs := o.QueryTable(new(Video))
	// query k=v
	for k, v := range query {
		// rewrite dot-notation to Object__Attribute
		k = strings.Replace(k, ".", "__", -1)
		qs = qs.Filter(k, v)
	}
	// order by:
	var sortFields []string
	if len(sortby) != 0 {
		if len(sortby) == len(order) {
			// 1) for each sort field, there is an associated order
			for i, v := range sortby {
				orderby := ""
				if order[i] == "desc" {
					orderby = "-" + v
				} else if order[i] == "asc" {
					orderby = v
				} else {
					return nil, 0, errors.New("Error: Invalid order. Must be either [asc|desc]")
				}
				sortFields = append(sortFields, orderby)
			}
			qs = qs.OrderBy(sortFields...)
		} else if len(sortby) != len(order) && len(order) == 1 {
			// 2) there is exactly one order, all the sorted fields will be sorted by this order
			for _, v := range sortby {
				orderby := ""
				if order[0] == "desc" {
					orderby = "-" + v
				} else if order[0] == "asc" {
					orderby = v
				} else {
					return nil, 0, errors.New("Error: Invalid order. Must be either [asc|desc]")
				}
				sortFields = append(sortFields, orderby)
			}
		} else if len(sortby) != len(order) && len(order) != 1 {
			return nil, 0, errors.New("Error: 'sortby', 'order' sizes mismatch or 'order' size is not 1")
		}
	} else {
		if len(order) != 0 {
			return nil, 0, errors.New("Error: unused 'order' fields")
		}
	}

	var l []orm.Params
	count, err = qs.Count()
	qs = qs.RelatedSel().OrderBy(sortFields...)
	if _, err = qs.Limit(limit, offset).Values(&l, fields...); err == nil {
		if len(fields) == 0 {
			for _, v := range l {
				if v["Scope"].(int64) == 0 {
					v["Sname"] = "本部门"
				} else if v["Scope"].(int64) == 1 {
					v["Sname"] = "全单位"
				} else if v["Scope"].(int64) == 2 {
					v["Sname"] = "全系统"
				} else if v["Scope"].(int64) == 3 {
					v["Sname"] = "指定用户"
				}
				ml = append(ml, v)
			}
		} else {
			// trim unused fields
			for _, v := range l {
				m := make(map[string]interface{})
				val := reflect.ValueOf(v)
				for _, fname := range fields {
					m[fname] = val.FieldByName(fname).Interface()
				}
				ml = append(ml, m)
			}
		}
		return ml, count, nil
	}
	return nil, 0, err
}

// UpdateVideo updates Video by Id and returns error if
// the record to be updated doesn't exist
func UpdateVideoById(m *Video) (err error) {
	o := orm.NewOrm()
	v := Video{Id: m.Id}
	// ascertain id exists in the database
	if err = o.Read(&v); err == nil {
		var num int64
		if num, err = o.Update(m); err == nil {
			fmt.Println("Number of records updated in database:", num)
		}
	}
	return
}

// DeleteVideo deletes Video by Id and returns error if
// the record to be deleted doesn't exist
func DeleteVideo(id string) (err error) {
	o := orm.NewOrm()
	v := Video{Id: id}

	// ascertain id exists in the database
	if err = o.Read(&v); err == nil {
		// var num int64
		if _, err = o.Delete(&Video{Id: id}); err == nil {
			seaweed.DeleteFile(v.Url)
			seaweed.DeleteFile(v.Img)
		}
	}
	return
}

// 软删除 Video by Id and returns error if
// the record to be deleted doesn't exist
func SoftDeleteVideo(id string, uname string) (err error) {
	o := orm.NewOrm()
	v := Video{Id: id}

	// ascertain id exists in the database
	if err = o.Read(&v); err == nil {
		v.Isdelete = 1
		v.Updater = uname
		v.Utime = time.Now()
		_, err = o.Update(&v)
	}
	return
}

func GetVideoByUrl(url string) (Video, error) {
	o := orm.NewOrm()
	var v Video

	err := o.QueryTable(new(Video)).Filter("url", url).One(&v)
	return v, err
}

//Desc 添加视频观看次数
//Param url 视频url
//return error
func AddVideoClicks(url string) error {
	o := orm.NewOrm()
	_, err := o.QueryTable(new(Video)).Filter("url", url).Update(orm.Params{"clicks": orm.ColValue(orm.ColAdd, 1)})
	return err
}

//根据orgid获取视频列表
func GetVideoByOrgid(user *User) (ml []interface{}, count int64, err error) {
	o := orm.NewOrm()
	video := new(Video)
	qs := o.QueryTable(video)
	qs = qs.Filter("Isdelete", 0).Filter("Status", 1).OrderBy("clicks")
	os := qs //单位全部视频
	ss := qs //系统全部视频
	us := qs //用户指定视频
	var l []Video
	//	dept, _ := GetUserDeptByUserId(uid)
	qs.Filter("scope", 0).Filter("Dept__Id", user.Dept[0].Id).Limit(-1).All(&l)
	rtmpserver := "http://" + beego.AppConfig.String("NginxServerAddress") + ":8080/"
	count, err = qs.Count()
	for k, v := range l {
		lc := make(map[string]interface{})
		lc["type"] = "video/flv"
		lc["index"] = k
		lc["id"] = v.Id
		lc["name"] = v.Title
		lc["url"] = v.Url
		lc["src"] = rtmpserver + v.Url
		lc["img"] = v.Img
		lc["longtime"] = v.Longtime
		ml = append(ml, lc)
	}
	beego.Debug(ml)
	//单位全部视频
	l = l[:0]
	pids := new([]string)
	GetParentOrg(user.Organization.Id, pids)
	os.Filter("Organization__Id", *pids).Limit(-1).All(&l)
	for k, v := range l {
		lc := make(map[string]interface{})
		lc["type"] = "video/flv"
		lc["index"] = k
		lc["id"] = v.Id
		lc["name"] = v.Title
		lc["url"] = v.Url
		lc["src"] = rtmpserver + v.Url
		lc["img"] = v.Img
		lc["longtime"] = v.Longtime
		ml = append(ml, lc)
	}
	beego.Debug(ml)
	//系统全部视频
	l = l[:0]
	ss.Filter("scope", 2).Limit(-1).All(&l)
	for k, v := range l {
		lc := make(map[string]interface{})
		lc["type"] = "video/flv"
		lc["index"] = k
		lc["id"] = v.Id
		lc["name"] = v.Title
		lc["url"] = v.Url
		lc["src"] = rtmpserver + v.Url
		lc["img"] = v.Img
		lc["longtime"] = v.Longtime
		ml = append(ml, lc)
	}
	beego.Debug(ml)
	//用户指定视频
	l = l[:0]
	ul := user.Video
	if len(ul) > 0 {
		us.Filter("scope", 3).Filter("Id__in", ul).Limit(-1).All(&l)
		for k, v := range l {
			lc := make(map[string]interface{})
			lc["type"] = "video/flv"
			lc["index"] = k
			lc["id"] = v.Id
			lc["name"] = v.Title
			lc["url"] = v.Url
			lc["src"] = rtmpserver + v.Url
			lc["img"] = v.Img
			lc["longtime"] = v.Longtime
			ml = append(ml, lc)
		}
	}
	beego.Debug(ml)
	return
}

//根据orgid获取视频列表
//若传递页数和每页显示数目，则返回限制，否则返回全部
func GetVideoListByOrgid(oid, page_size int64, page ...int64) (videos []Video, count int64, err error) {
	o := orm.NewOrm()
	video := new(Video)
	qs := o.QueryTable(video).Filter("Organization__ID", oid)
	qs.Limit(-1).All(&videos)
	count, err = qs.Count()
	var offset int64
	if len(page) > 0 {
		if page[0] <= 1 {
			offset = 0
		} else {
			offset = (page[0] - 1) * page_size
		}
		qs.Limit(page_size, offset).OrderBy("-ctime").All(&videos)
	}
	return
}

//获取所有视频列表
func GetVideolist() (videos []interface{}, count int64, err error) {
	o := orm.NewOrm()
	video := new(Video)
	qs := o.QueryTable(video)
	qs = qs.Filter("Isdelete", 0).Filter("Status", 1)
	var l []Video
	qs.Limit(-1).All(&l)
	count, err = qs.Count()
	rtmpserver := "http://" + beego.AppConfig.String("NginxServerAddress") + ":8080/"
	for k, v := range l {
		lc := make(map[string]interface{})
		lc["type"] = "video/flv"
		lc["index"] = k
		lc["id"] = v.Id
		lc["name"] = v.Title
		lc["url"] = v.Url
		lc["src"] = rtmpserver + v.Url
		lc["img"] = v.Img
		lc["longtime"] = v.Longtime
		videos = append(videos, lc)
	}

	return
}

//GetUsedDiskPercent 查看单位已用空间的百分比
//org 单位
//int64 已用空间百分比
func GetUsedDiskPercent(org Organization) int64 {
	o := orm.NewOrm()
	var maps []orm.Params
	sql := "SELECT a.name,a.userlimit,sum(b.size)" +
		" FROM sys_organization a left JOIN vid_video b on " +
		" a.id=b.organization_id WHERE a.id=?" +
		" GROUP BY a.name,a.userlimit"
	_, err := o.Raw(sql, org.Id).Values(&maps)
	if err == nil {
		used, _ := maps[0]["sum"].(float64)
		if org.Userlimit == 0 {
			return 0
		}
		var f2 = float64(org.Userlimit)
		percent := (used / (f2 * 1024 * 1024)) * 100
		return int64(percent)
	} else {
		return 0
	}
}

//Desc 根据点播资源id删除用户授权
//Param  lid 点播资源id
//return error
func DeleteUserVideoByVideoId(lid string) (err error) {
	o := orm.NewOrm()
	_, err = o.Raw("DELETE FROM sys_user_vid_videos WHERE vid_Video_id=?", lid).Exec()
	return
}

//分配视频用户
func AddUserVideo(userid, vid string) (int64, error) {
	o := orm.NewOrm()
	video := Video{Id: vid}
	user := User{Id: userid}
	m2m := o.QueryM2M(&user, "Video")
	num, err := m2m.Add(&video)
	return num, err
}
